package org.bukkit.pm.rspawn;
import java.util.logging.Level;

import org.bukkit.Location;
import org.bukkit.entity.Player;


/**
 * This class is used to map player spawn points
 * @author patamau
 *
 */
public class RSpawnPlayer {
	
	private static final String SSEP = ":";
	public static final long SPAWN_TIMEOUT = 500; //time to wait before actual teleporting

	public static final int 
		T_DEF = 0, //default spawn point: do not interfer in teleporting
		T_HOME = 1, //use player home
		T_RAND = 2; //use random spawn
	
	private String 
		_name;
	private int 
		_type; //RSpawn type
	private Location
		_loc = null; //cached location for player
	private double _x, _y, _z; //coordinates
	
	public RSpawnPlayer(String n, int t, double x, double y, double z){
		_name = n;
		_type = t;
		_x = x;
		_y = y;
		_z = z;
	}
	
	public String getName(){
		return _name;
	}
	
	public int getType(){
		return _type;
	}
	
	public Location getLocation(Player p){
		if(_loc==null && _type!=T_DEF){
			//create custom location and cache it
			_loc = new Location(p.getWorld(),_x,_y,_z);
		}
		return _loc;
	}
	
	public void sendMessage(String msg, RSpawnPlugin plugin){
		Player p = plugin.getServer().getPlayer(_name);
		if(p!=null){
			p.sendMessage(msg);
		}else{
			plugin.log(Level.FINE,"unable to send message: no such player '"+_name+"'");
		}
	}
	
	public String serialize(){
		return _name+SSEP+_type+SSEP+_x+SSEP+_y+SSEP+_z+SSEP;
	}
	
	public static RSpawnPlayer parse(String serialized, RSpawnPlugin plugin){
		String[] split = serialized.split(SSEP);
		StringBuffer sb = new StringBuffer();
		for(String s: split){
			sb.append(s);
			sb.append(" ");
		}
		plugin.log(Level.INFO,"loading "+sb.toString());
		//check serialization data
		if(split.length<5){
			plugin.log(Level.WARNING, "wrong RSpawn player format");
			return null;
		}
		String n = split[0]; //name
		int t; //type		
		double x=0, y=0, z=0; //location coordinates
		try{
			t = Integer.parseInt(split[1]);
			if(t==T_HOME){ //parse only if home type
				x = Double.parseDouble(split[2]);
				y = Double.parseDouble(split[3]);
				z = Double.parseDouble(split[4]);
			}
		}catch(NumberFormatException e){
			plugin.log(Level.WARNING, "wrong values for player "+n);
			return null;
		}
		//---
		return new RSpawnPlayer(n, t, x, y, z);
	}
	
	/**
	 * Compare player names
	 */
	public boolean equals(Object o){
		if(o instanceof RSpawnPlayer){
			return ((RSpawnPlayer)o)._name==_name;
		}
		return false;
	}

	public void setLocation(Location location) {
		_loc = location;
		_x = _loc.getX();
		_y = _loc.getY();
		_z = _loc.getZ();
	}
	
	public void setType(int type){
		_type = type;
	}
}
